<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="分组名称" prop="groupName">
        <el-input v-model="queryParams.groupName" placeholder="请输入分组名称" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <!-- 防止仅有一个输入框时光标在那一个输入框里时按回车出现“正在加载系统资源，请耐心等待” -->
      <input hidden />

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['user:group:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['user:group:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['user:group:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getDataList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="60" />
      <el-table-column label="分组名称" prop="groupName" width="150" />
      <el-table-column label="分组成员" prop="usersName"></el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
           >查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['user:group:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['user:group:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getDataList" />
    <!-- 添加或编辑弹框 -->
    <el-dialog :title="addDialogTitle" :visible.sync="addDialogVisible" width="500px" append-to-body
      @closed="handleAddDialogClosed">
      <el-form ref="addFormRef" :model="addDialogFormData" :rules="addDialogFormRules" size="medium"
        label-width="100px">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="addDialogFormData.groupName" placeholder="请输入分组名称" clearable> </el-input>
        </el-form-item>
        <el-form-item label="分组成员" prop="userIdArr">
          <el-select v-model="addDialogFormData.userIdArr" placeholder="请选择5个分组成员" multiple filterable clearable
            style="width: 100%">
            <el-option v-for="(item, index) in scUserList" :key="index" :label="item.nickName" :value="item.userId"
              :disabled="addDialogFormData.userIdArr.length >= 5 && !addDialogFormData.userIdArr.includes(item.userId)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleAddDialogCancel">取消</el-button>
        <el-button type="primary" @click="handleAddDialogConfirm">确定</el-button>
      </div>
    </el-dialog>
    <!-- 查看弹框 -->
    <el-dialog :title="viewDialogData.groupName" :visible.sync="viewDialogVisible" width="500px" append-to-body>
      <el-table :data="viewDialogData.userList">
        <el-table-column label="用户ID" prop="userId" />
        <el-table-column label="用户昵称" prop="userName" />
      </el-table>
      <div slot="footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 分组管理
// 每个分组固定5个“生产”角色的用户
// 每个分组固定5个“生产”角色的用户
// 每个分组固定5个“生产”角色的用户
// 每个分组固定5个“生产”角色的用户
// 每个分组固定5个“生产”角色的用户

import { postUserGroupList, postUserGroupInfo, postUserGroupRemove, getUserListRole, postUserGroupAdd, postUserGroupEdit } from '@/api/group'

export default {
  name: 'GroupList',
  data() {
    // 验证添加或编辑弹框里的分组成员
    const validateUserIdArr = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('请选择5个分组成员!'))
      } else {
        callback()
      }
    }

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: undefined,
      },
      // 数据列表
      dataList: [],

      // 生产角色下所有用户列表
      scUserList: [],

      // 添加弹框标题
      addDialogTitle: '',
      // 添加弹框是否显示
      addDialogVisible: false,
      // 添加弹框表单参数
      addDialogFormData: {
        id: undefined,
        groupName: undefined,
        userIdArr: [],
      },
      // 添加弹框表单校验
      addDialogFormRules: {
        groupName: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
        userIdArr: [
          { required: true, type: 'array', message: '请选择5个分组成员', trigger: 'change' },
          { validator: validateUserIdArr, trigger: 'change' },
        ],
      },

      // 查看对话框是否显示
      viewDialogVisible: false,
      // 查看对话框数据
      viewDialogData: {},
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    /** 查询列表 */
    getDataList() {
      this.loading = true
      postUserGroupList(this.queryParams).then((response) => {
        response.rows.forEach((item) => {
          item.user1 = JSON.parse(item.step1)
          item.user2 = JSON.parse(item.step2)
          item.user3 = JSON.parse(item.step3)
          item.user4 = JSON.parse(item.step4)
          item.user5 = JSON.parse(item.step5)
          item.usersName =
            item.user1.userName + '、' + item.user2.userName + '、' + item.user3.userName + '、' + item.user4.userName + '、' + item.user5.userName
          item.userList = [item.user1, item.user2, item.user3, item.user4, item.user5]
        })
        this.dataList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getDataList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids
      this.$modal
        .confirm('是否确认删除分组ID为"' + ids + '"的数据项？')
        .then(function () {
          return postUserGroupRemove({ ids })
        })
        .then(() => {
          this.getDataList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => { })
    },

    /** 添加弹框关闭了 */
    handleAddDialogClosed() {
      // console.log('添加弹框关闭了')
      this.addDialogFormData = {
        id: undefined,
        groupName: undefined,
        userIdArr: [],
      }
      this.$refs.addFormRef.resetFields()
    },
    /** 新增按钮操作 */
    async handleAdd() {
      await this.funGetUserListRole()
      this.addDialogVisible = true
      this.addDialogTitle = '添加分组'
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      let rowData

      if (row.id) {
        rowData = row
      } else {
        rowData = this.dataList.find((item) => item.id === this.ids[0])
      }

      await this.funGetUserListRole()

      this.addDialogFormData.id = rowData.id
      this.addDialogFormData.groupName = rowData.groupName
      this.addDialogFormData.userIdArr = rowData.userIds.split(',').map(Number)

      this.addDialogVisible = true
      this.addDialogTitle = '修改分组'
    },
    /** 获取生产角色下所有用户 */
    async funGetUserListRole() {
      const result = await getUserListRole({ codes: 'shengchan' })
      this.scUserList = result.data
      console.log(this.scUserList, 'this.scUserList')
    },
    // 添加或编辑弹框取消
    handleAddDialogCancel() {
      this.addDialogVisible = false
    },
    funGetUserJson(userId) {
      const userInfo = this.scUserList.find((item) => item.userId === userId)
      return JSON.stringify({ userId: userInfo.userId, userName: userInfo.nickName })
    },
    // 添加或编辑弹框确定
    handleAddDialogConfirm() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return

        console.log(JSON.stringify(this.addDialogFormData))
        const requestData = {
          id: this.addDialogFormData.id,
          groupName: this.addDialogFormData.groupName,
          step1: this.funGetUserJson(this.addDialogFormData.userIdArr[0]),
          step2: this.funGetUserJson(this.addDialogFormData.userIdArr[1]),
          step3: this.funGetUserJson(this.addDialogFormData.userIdArr[2]),
          step4: this.funGetUserJson(this.addDialogFormData.userIdArr[3]),
          step5: this.funGetUserJson(this.addDialogFormData.userIdArr[4]),
        }
        // console.log(requestData)

        this.loading = true
        if (requestData.id) {
          const result = await postUserGroupEdit(requestData)
          this.$modal.msgSuccess('修改成功')
        } else {
          const result = await postUserGroupAdd(requestData)
          this.$modal.msgSuccess('添加成功')
        }
        this.loading = false
        this.getDataList()
        this.handleAddDialogCancel()
      })
    },
    // 查看
    handleView(row) {
      // console.log(JSON.parse(JSON.stringify(row)))
      this.viewDialogData = row
      this.viewDialogVisible = true
    },
  },
}
</script>

<style lang="scss" scoped></style>
